#pragma once

#include <iostream>
#include <string>
#include <memory>
#include <sys/epoll.h>

#include "Log.hpp"
#include "Socket.hpp"
#include "Common.hpp"
#define NUM 1024
#define gdefaultfd -1
#define MAX 4096
using namespace LogMudule;
using namespace SocketMudule;
class epollServer
{
    static const int revs_num = 64;
public:
    epollServer(int port)
        : _port(port), _listen_socket(std::make_unique<TcpSocket>()), _is_running(false),_epfd(gdefaultfd)
    {
    }
    ~epollServer()
    {
        _listen_socket->Close();
    }
    void Init()
    {
        _listen_socket->BuildTcpSocketMethod(_port);
        // 1. 创建epoll模型
        _epfd = epoll_create(256);
        if(_epfd < 0)
        {
            LOG(LogLevel::ERROR) << "epoll_create error";
            exit(EPOLL_ERR);
        }
        // 2. 注册listensockfd到epoll模型
        struct epoll_event ev;
        ev.events = EPOLLIN;
        ev.data.fd = _listen_socket->fd();
        int n = epoll_ctl(_epfd, EPOLL_CTL_ADD, _listen_socket->fd(), &ev);
        if(n < 0)
        {
            LOG(LogLevel::ERROR) << "epoll_ctl error";
            exit(EPOLL_ERR);
        }
    }
    void Start()
    {
        _is_running = true;
        int timeout = -1; // 1s
        while (_is_running)
        {
            // 我们不能让accept来阻塞检测新连接到来，而应该让select来负责进行就绪事件的检测
            int n = epoll_wait(_epfd, _revs, revs_num, timeout);
            switch (n)
            {
            case 0:
                std::cout << "epoll_wait timeout" << std::endl;
                break;
            case -1:
                perror("epoll_wait error");
                break;
            default:
                std::cout << "有事件就绪...., timeout " << std::endl;
                HandlerEvent(n); // 把已经就绪事件，派发给不同的处理函数
                break;
            }
        }
        _is_running = false;
    }
    //
    void Accept()
    {
        InetAddr client;
        // listen_socket有新连接到来
        int newfd = _listen_socket->Accepter(&client);
        if (newfd < 0)
        {
            std::cout << "accept error" << std::endl;
            return;
        }
        else
        {
            std::cout << "Get new client " << newfd << " connected" << std::endl;
            // 我们需要将这个新的newfd添加给epoll，让epoll帮我们进行监管
            struct epoll_event ev;
            ev.events = EPOLLIN;
            ev.data.fd = newfd;
            int n = epoll_ctl(_epfd, EPOLL_CTL_ADD, newfd, &ev);
            if(n < 0)
            {
                LOG(LogLevel::ERROR) << "epoll_ctl error";
                close(newfd);
            }
            LOG(LogLevel::DEBUG) << "add new client " << newfd << " to epoll";
        }
    }
    //
    void Recv(int fd)
    {
        // 合法的，就绪的，普通的fd
        char buffer[1024];
        // 这里的recv，对不对呢？？？不完善，必须有协议 ----> 有bug！！！！！
        ssize_t n = recv(fd, buffer, sizeof(buffer) - 1, 0);
        if (n > 0)
        {
            buffer[n] = '\0';
            std::cout << "client " << buffer << std::endl;
            // 把读到的信息，在回显回去
            std::string message = "echo# " + std::string(buffer);
            send(fd, message.c_str(), message.size(), 0); // bug
        }
        else if (n == 0)
        {
            LOG(LogLevel::DEBUG) << "客户端退出，sockfd： " << fd;
            // 客户端退出，从epoll中移除
            int m = epoll_ctl(_epfd, EPOLL_CTL_DEL, fd, nullptr);
            if(m < 0)
            {
                LOG(LogLevel::ERROR) << "epoll_ctl error";
                return;
            }
            LOG(LogLevel::DEBUG) << "epoll_ctl SUCESS";
            close(fd);
        }
        else
        {
            LOG(LogLevel::DEBUG) << "客户端读取退出，sockfd： " << fd;
            int m = epoll_ctl(_epfd, EPOLL_CTL_DEL, fd, nullptr);
            if(m < 0)
            {
                LOG(LogLevel::ERROR) << "epoll_ctl error";
                return;
            }
            LOG(LogLevel::DEBUG) << "epoll_ctl SUCESS";
            close(fd);
        }
    }


    void HandlerEvent(int rnum)
    {
        for (int i = 0; i < rnum; i++)
        {
            int events = _revs[i].events;
            int fd = _revs[i].data.fd;
            if(fd == _listen_socket->fd())
            {
                if(events & EPOLLIN)
                {
                    // linsten_socket有新连接到来
                    Accept();
                }
            }
            else
            {
                // 普通fd准备就绪
                if(events & EPOLLIN)
                {
                    // 读事件就绪
                    Recv(fd);
                }
                // else if(events & EPOLLOUT)
            }
        }
    }

private:
    uint16_t _port;
    std::unique_ptr<Socket> _listen_socket;
    bool _is_running;
    int _epfd;
    struct epoll_event _revs[revs_num];
};